package com.lxz.jucdemo.pc;

import javax.swing.plaf.PanelUI;

/**
 * @Author: 刘新智
 * @Date: 2025/10/25 12:29
 * @Description:
 * @Version: v1.0
 */
public class ProductConsumeTest1 {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.increment();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.decrement();
            }
        },"B").start();
    }

}

class Data{
    private int number;

    public synchronized void increment(){
        try {
            // 1. 判断等待
            while (number != 0){
                this.wait();
            }
            // 2. 业务代码
            number++;
            System.out.println(Thread.currentThread().getName()+"正在执行："+ number);
            //3. 通知其他线程
            this.notifyAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    public synchronized void decrement(){
        try {
            // 1. 判断等待
            while (number == 0){
                this.wait();
            }
            // 2. 业务代码
            number--;
            System.out.println(Thread.currentThread().getName()+"正在执行："+ number);
            //3. 通知其他线程
            this.notifyAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
